// miniprogram/pages/wait/done.js
import WxValidate from "../../utils/vendor/WxValidate"
import U from "../../utils/index"
import { IO } from "../../utils/vendor/ramda-fantasy"
import * as R from "ramda"
const pageConfig = {
  maxUploadNum: 1,
};
const validator = {
  rules: {
    complete_info: {
      required: true,
    },
    complete_image_url: {
      required: true,
    },
  },
  messages: {
    complete_info: {
      required: '请输入任务完成情况',
    },
    complete_image_url: {
      required: '请上传图片凭证',
    },
  },
};
const wxValidate = new WxValidate(validator.rules, validator.messages);

const requestAllandHandle = data => () => R.composeP(
  res => U.reqPost({
    url: '/task/comlete_task',
    data: res
  }),
  res => Object.assign({}, data, { complete_image_url: res.data.img }),
  () => U.uploadFile({ filePath: data.complete_image_url })
)()
const handleAllRequest = data => U.handleRequest({
  isShowSuccessMsg: true,
  successMsg: '完成任务成功！'
}, requestAllandHandle(data));


Page({

  /**
   * 页面的初始数据
   */
  data: {
    taskId: null,
    form: {},
    tempFilePaths: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      taskId: Number(options.taskId),
      [ 'form.task_id']: Number(options.taskId),
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  setFormData(e) {
    U.setFormData(e).run(this);
  },
  onClickUploadBtn(){
    R.ifElse(
      () => pageConfig.maxUploadNum === this.data.tempFilePaths.length,
      () => wx.showToast({
        title: `最多只能传${pageConfig.maxUploadNum}张图片`,
        icon: 'none',
      }),
      R.composeP(
        () => this.setData({ ['form.complete_image_url']: this.data.tempFilePaths[0] }),
        res => this.setData({ tempFilePaths: R.concat(this.data.tempFilePaths, res.tempFilePaths) }),
        () => U.wxP(wx.chooseImage, {
          count: pageConfig.maxUploadNum - this.data.tempFilePaths.length, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        })
      )
    )();
  },
  //点击图片预览图片
  onClickImg(e){
    (paths => wx.previewImage({
      urls: paths,
      current: paths[e.target.dataset.index]
    }))(this.data.tempFilePaths);
  },
  //点击叉删除图片
  onClickClear(e){
    this.setData({
      tempFilePaths: R.remove(e.target.dataset.index, 1, this.data.tempFilePaths),
      // 只能传一张，所以删除肯定是清空form里的图片
      ['form.complete_image_url']: null,
    })
  },
  onSubmit(e) {
    R.compose(
      U.runIO,
      U.handleError,
      R.map(
        R.compose(
          U.fork,
          R.map(R.compose(U.runIO, U.backReqSuc)),
          handleAllRequest
        )
      ),
      U.validate(wxValidate),
      R.tap(form => this.setData({ form })),
      R.map(U.trim),
    )(this.data.form);
  },
})
